<template>
  <div class="phone-management">
    <el-card class="box-card">
      <div slot="header" class="card-header">
        <span>学号管理</span>
        <el-button 
          type="primary" 
          size="small" 
          icon="el-icon-plus" 
          @click="showAddPhoneDialog">
          添加学号
        </el-button>
      </div>
      
      <!-- 手机号列表 -->
      <div v-loading="loading" class="phone-list">
        <el-empty v-if="!snoList.length" description="暂无学号"></el-empty>
        <el-card
          v-for="item in snoList"
          :key="item.phone"
          class="phone-card"
          :class="{ 'registered': item.register === 1 }"
          shadow="hover"
        >
          <div class="phone-content">
            <div class="phone-info">
              <span 
                class="phone-value clickable" 
                @click="showUserInfo(item.sno)"
              >
                {{ item.sno }}
              </span>
            </div>
            <div class="phone-actions">
              <el-button
                type="text"
                icon="el-icon-delete"
                class="delete-btn"
                @click="handleDeletePhone(item.phone)"
              >
                删除
              </el-button>
            </div>
          </div>
        </el-card>
      </div>
    </el-card>
    
    <!-- 添加手机号对话框 -->
    <el-dialog
      title="添加学号"
      :visible.sync="addPhoneDialogVisible"
      width="500px">
      <el-form 
        ref="phoneForm" 
        :model="phoneForm" 
        :rules="phoneRules" 
        label-width="100px">
        <!-- 添加模式选择 -->
        <el-form-item label="添加方式">
          <el-radio-group v-model="phoneForm.mode">
            <el-radio label="single">单个添加</el-radio>
            <el-radio label="batch">批量添加</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 单个添加表单 -->
        <el-form-item 
          label="手机号" 
          prop="phone" 
          v-if="phoneForm.mode === 'single'">
          <el-input 
            v-model="phoneForm.phone" 
            placeholder="请输入手机号"
            maxlength="11">
          </el-input>
        </el-form-item>

        <!-- 批量添加表单 -->
        <el-form-item 
          label="手机号列表" 
          prop="snoList"
          v-if="phoneForm.mode === 'batch'">
          <el-input
            type="textarea"
            :rows="8"
            placeholder="请输入学号列表"
            v-model="phoneForm.phoneList">
          </el-input>
          <div class="form-tip">每行输入一个学号</div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addPhoneDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitPhoneForm" :loading="submitting">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 添加用户信息对话框 -->
    <el-dialog
      title="用户信息"
      @close="handleCloseUserInfo"
      :visible.sync="userInfoVisible"
      width="400px">
      <div :v-loading="userInfoLoading">
        <div v-if="currentUser" class="user-info">
          <div class="user-avatar">
            <el-avatar 
              :size="80" 
              :src="currentUser.avatar || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'"
            ></el-avatar>
          </div>
          <el-descriptions :column="1" border>
            <el-descriptions-item label="用户名">{{ currentUser.nickname || '-' }}</el-descriptions-item>
            <el-descriptions-item label="学号">{{ currentUser.sno }}</el-descriptions-item>
            <el-descriptions-item label="用户类型">
              <el-tag :type="getUserTypeTag(currentUser.role)">
                {{ getUserTypeName(currentUser.role) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="注册时间">
              {{ formatDate(currentUser.createTime) || '-' }}
            </el-descriptions-item>
            <!-- <el-descriptions-item label="所属部门">{{ currentUser.department || '-' }}</el-descriptions-item> -->
            <!-- <el-descriptions-item label="账号状态">
              <el-tag :type="currentUser.status === 1 ? 'success' : 'danger'">
                {{ currentUser.status === 1 ? '正常' : '禁用' }}
              </el-tag>
            </el-descriptions-item> -->
          </el-descriptions>
        </div>
        <el-empty v-else description="未找到用户信息"></el-empty>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import httpInstance from '@/utils/http';

export default {
  name: 'PhoneManagement',
  data() {
    // 手机号验证规则
    const validatePhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入学号'));
        return;
      }
      if (!/^20\d{2}1204140\d{3}$/.test(value)) {
        callback(new Error('请输入正确的学号'));
        return;
      }
      callback();
    };

    return {
      loading: false,
      snoList: [],
      addPhoneDialogVisible: false,
      phoneForm: {
        mode: 'single', // 默认单个添加
        phone: '', // 单个手机号
        phoneList: '' // 批量手机号
      },
      submitting: false,
      phoneRules: {
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: validatePhone, trigger: 'blur' }
        ],
        phoneList: [
          { required: true, message: '请输入手机号列表', trigger: 'blur' }
        ]
      },
      userInfoVisible: false,
      userInfoLoading: false,
      currentUser: null
    };
  },
  
  created() {
    this.fetchPhoneList();
  },
  
  methods: {
    // 获取手机号列表
    async fetchPhoneList() {
      this.loading = true;
      try {
        const res = await httpInstance.post('/api/sys/getSno');
        
        if (res.code === 200) {
          this.snoList = res.data || [];
        } else {
          this.$message.error(res.msg || '获取学号列表失败');
        }
      } catch (error) {
        this.$message.error('获取学号列表失败');
      } finally {
        this.loading = false;
      }
    },
    
    // 显示添加手机号对话框
    showAddPhoneDialog() {
      this.addPhoneDialogVisible = true;
      this.phoneForm = {
        mode: 'single',
        phone: '',
        phoneList: ''
      };
      // 重置表单验证
      this.$nextTick(() => {
        this.$refs.phoneForm && this.$refs.phoneForm.clearValidate();
      });
    },
    
    // 提交添加手机号表单
    async submitPhoneForm() {
      if (this.phoneForm.mode === 'single') {
        // 单个手机号验证
        try {
          await this.$refs.phoneForm.validateField('phone');
        } catch (error) {
          return;
        }
        
        // 提交单个手机号
        await this.submitSinglePhone();
      } else {
        // 批量添加验证
        if (!this.phoneForm.phoneList.trim()) {
          this.$message.warning('请输入手机号');
          return;
        }
        
        // 提交批量手机号
        await this.submitBatchPhones();
      }
    },

    // 提交单个手机号
    async submitSinglePhone() {
      this.submitting = true;
      try {
        const res = await httpInstance.post('/api/sys/addPhone', [this.phoneForm.phone]);
        
        if (res.code === 200) {
          this.$message.success('添加成功');
          this.addPhoneDialogVisible = false;
          this.fetchPhoneList();
        } else {
          this.$message.error(res.msg || '添加失败');
        }
      } catch (error) {
        console.error('添加失败:', error);
        this.$message.error('添加失败');
      } finally {
        this.submitting = false;
      }
    },

    // 提交批量手机号
    async submitBatchPhones() {
      // 处理手机号列表
      const phones = this.phoneForm.phoneList
        .split('\n')
        .map(p => p.trim())
        .filter(p => p);
      
      // 验证手机号格式
      const phoneRegex = /^1[3-9]\d{9}$/;
      const invalidPhones = phones.filter(p => !phoneRegex.test(p));
      
      if (invalidPhones.length > 0) {
        this.$message.error(`以下手机号格式不正确:\n${invalidPhones.join('\n')}`);
        return;
      }
      
      this.submitting = true;
      try {
        const res = await httpInstance.post('/api/sys/addPhone', phones);
        
        if (res.code === 200) {
          this.$message.success(`成功添加 ${res.data.successCount} 个手机号`);
          if (res.data.invalidCount > 0) {
            this.$message.warning(`${res.data.invalidCount} 个手机号添加失败`);
          }
          this.addPhoneDialogVisible = false;
          this.fetchPhoneList();
        } else {
          this.$message.error(res.msg || '添加失败');
        }
      } catch (error) {
        console.error('添加失败:', error);
        this.$message.error('添加失败');
      } finally {
        this.submitting = false;
      }
    },
    
    // 处理删除手机号
    async handleDeletePhone(phone) {
      try {
        await this.$confirm(`确定要删除手机号 ${phone} 吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        
        const res = await httpInstance.post(`/api/sys/delPhone/${phone}`);
        
        if (res.code === 200) {
          this.$message.success('删除成功');
          this.fetchPhoneList();
        } else {
          this.$message.error(res.msg || '删除失败');
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除手机号失败:', error);
          this.$message.error('删除失败');
        }
      }
    },

    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return '-';
      const date = new Date(dateStr);
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      });
    },

    // 处理对话框关闭
    handleCloseUserInfo() {
      this.userInfoVisible = false;
      this.currentUser = null;
    },

    // 修改后的显示用户信息方法
    async showUserInfo(phone) {
      this.userInfoVisible = true;
      this.userInfoLoading = true;
      this.currentUser = null;
      
      try {
        const res = await httpInstance.post(`/api/user/getDetailByPhone/${phone}`);
        if (res.code === 200) {
          this.currentUser = res.data;
        } else {
          this.$message.error(res.msg || '获取用户信息失败');
        }
      } catch (error) {
        console.error('获取用户信息失败:', error);
        this.$message.error('获取用户信息失败');
      } finally {
        this.userInfoLoading = false;
      }
    },

    // 获取用户类型标签样式
    getUserTypeTag(role) {
      const types = {
        1: 'info',    // 普通用户
        2: 'success', // 社团管理员
        3: 'danger'   // 超级管理员
      };
      return types[role] || 'info';
    },

    // 获取用户类型名称
    getUserTypeName(role) {
      const types = {
        1: '普通用户',
        2: '社团管理员',
        3: '超级管理员'
      };
      return types[role] || '未知';
    }
  }
};
</script>

<style scoped>
.phone-management {
  padding: 10px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.phone-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 16px;
  padding: 16px;
}

.phone-card {
  transition: all 0.3s;
  border: 1px solid #EBEEF5;
}

.phone-card.registered {
  border-left: 4px solid #67C23A;
}

.phone-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px;
}

.phone-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.phone-value {
  font-family: monospace;
  font-size: 16px;
  color: #606266;
}

.status-tag {
  font-size: 12px;
}

.phone-actions {
  display: flex;
  gap: 8px;
  align-items: center;
}

.delete-btn {
  color: #F56C6C;
}

.delete-btn:hover {
  color: #f78989;
}

.form-tip {
  margin-top: 5px;
  color: #909399;
  font-size: 12px;
}

/* 添加新样式 */
.el-radio-group {
  margin-bottom: 15px;
}

.clickable {
  cursor: pointer;
  transition: color 0.3s;
}

.clickable:hover {
  color: #409EFF;
}

.user-info {
  padding: 20px;
}

.user-avatar {
  text-align: center;
  margin-bottom: 20px;
}

.el-descriptions {
  margin-top: 20px;
}

/* 调整描述列表的样式 */
:deep(.el-descriptions-item__label) {
  width: 100px;
  text-align: right;
  font-weight: bold;
}

:deep(.el-descriptions-item__content) {
  padding: 12px;
}

.user-detail {
  padding: 20px;
}

.user-header {
  text-align: center;
  margin-bottom: 30px;
}

.user-name {
  margin: 15px 0 0;
  font-size: 18px;
  color: #303133;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
  padding: 0 20px;
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.info-item.full-width {
  grid-column: span 2;
}

.info-label {
  font-size: 13px;
  color: #909399;
}

.info-value {
  font-size: 14px;
  color: #303133;
}

.el-dialog {
  border-radius: 8px;
}

.el-dialog__body {
  padding: 0;
}
</style>